<script src="../../icons/index.js"></script>
<template>
  <div class="app-container">
    <!--查询表单-->
    <el-form :inline="true" class="demo-form-inline" size="small">
      <el-form-item label="爬虫名称">
        <el-autocomplete
          v-model="searchObj.codeName"
          :fetch-suggestions="querySearchAsync"
          :trigger-on-focus="false"
          placeholder="请输入爬虫名称"
          clearable
          @select="fetchDataChange(1)"
          @keyup.enter="fetchDataChange(1)"
        />
      </el-form-item>

      <el-form-item label="项目名称" label-width="80px">
        <el-select v-model="searchObj.projectName" clearable placeholder="请选择项目" @change="fetchData">
          <el-option
            v-for="item in projectNameList"
            :key="item.projectName"
            :label="item.projectName"
            :value="item.projectName"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="服务器" label-width="80px">
        <el-select v-model="searchObj.machine" clearable placeholder="请选择服务器" @change="fetchData">
          <el-option
            v-for="item in machineList"
            :key="item.machine"
            :label="item.machine"
            :value="item.machine"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="负责人" label-width="80px">
        <el-select v-model="searchObj.person" clearable placeholder="请选择负责人" @change="changePerson">
          <el-option
            v-for="item in personList"
            :key="item.person"
            :label="item.person"
            :value="item.person"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="爬虫类型" label-width="80px">
        <el-select v-model="searchObj.spiderType" placeholder="请选择爬虫类型" @change="fetchData">
          <el-option
            v-for="item in spiderTypeList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <br>

      <el-form-item label="运行时间">
        <div class="block">
          <el-date-picker
            v-model="gmtCreate"
            type="daterange"
            align="center"
            unlink-panels
            value-format="yyyy-MM-dd"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            :picker-options="pickerOptions"
            style="width: 280px"
            @change="changeGmtCreate"
          />
        </div>
      </el-form-item>
      <br>
      <el-form-item label="爬虫语言">
        <el-radio-group v-model="searchObj.isJava" @change="fetchDataChange(1)">
          <el-radio :label="-1">全部</el-radio>
          <el-radio :label="0">Python</el-radio>
          <el-radio :label="1">Java</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" style="display: flex; justify-content: space-between; margin-bottom: 8px;">
      <el-col :span="1.5">
        <el-button
          ref="fetchData"
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="fetchData"
        >
          查询数据
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          ref="resetData"
          type="warning"
          icon="el-icon-refresh"
          size="mini"
          @click="resetData"
        >
          重置数据
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          ref="toppingData"
          type="warning"
          plain
          icon="el-icon-upload2"
          size="mini"
          @click="toppingData"
        >
          置顶数据
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          ref="unToppingData"
          type="info"
          plain
          icon="el-icon-download"
          size="mini"
          @click="unToppingData"
        >
          取消置顶
        </el-button>
      </el-col>
      <div class="right-toolbarClass">
        <right-toolbar @queryTable="fetchData" />
      </div>
    </el-row>

    <!--列表 height="600"-->
    <el-table
      ref="tableList"
      v-loading="loading"
      :data="list"
      :header-cell-style="headStyle"
      :cell-style="cellStyle"
      :default-sort="{prop: 'updateCount', order: 'descending'}"
      @sort-change="handleSortChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="70" align="center" />

      <el-table-column prop="codeName" align="center" label="爬虫名称">
        <template slot-scope="scope">
          <a v-if="scope.row.url" :href="scope.row.url" target="_blank" rel="noreferrer noopener nofollow" style="color: #328df3">{{ scope.row.codeName }}</a>
          <a v-else href="#" rel="noreferrer noopener nofollow" style="color: #328df3">{{ scope.row.codeName }}</a>
        </template>
      </el-table-column>
      <el-table-column prop="projectName" align="center" label="项目名称" width="150" />
      <el-table-column prop="machine" align="center" label="所属服务器" width="150" />
      <el-table-column prop="person" align="center" label="负责人" width="120">
        <template slot-scope="scope">
          <el-select v-model="scope.row.person" size="small" @change="updatePerson(scope.row)">
            <el-option
              v-for="item in personList"
              :key="item.person"
              :label="item.person"
              :value="item.person"
            />
          </el-select>
        </template>
      </el-table-column>

      <el-table-column prop="updateCount" align="center" label="更新数量" width="100" sortable="custom">
        <template slot-scope="scope">
          <span v-if="scope.row.updateCount > 0" style="color: blue">{{ scope.row.updateCount }}</span>
          <span v-else>{{ scope.row.updateCount }}</span>
        </template>
      </el-table-column>

      <el-table-column prop="count" align="center" label="新增数量" width="110" sortable="custom" />

      <el-table-column prop="lastTime" align="center" label="最近运行时间" width="150" sortable="custom">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.lastTime == 0" type="success">
            今天
          </el-tag>
          <el-tag v-if="scope.row.lastTime != null && scope.row.lastTime <= 3 && scope.row.lastTime > 0" type="success">
            {{ scope.row.lastTime }}天前
          </el-tag>
          <el-tag v-if="scope.row.lastTime > 3 && scope.row.lastTime <= 7" type="warning">
            {{ scope.row.lastTime }}天前
          </el-tag>
          <el-tag v-if="scope.row.lastTime > 7 && scope.row.lastTime <= 15" type="info">
            {{ scope.row.lastTime }}天前
          </el-tag>
          <el-tag v-if="scope.row.lastTime > 15" type="danger">
            {{ scope.row.lastTime }}天前
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="remarks" align="center" label="备注" width="200">
        <template slot-scope="scope">
          <el-input v-model="scope.row.remarks" type="textarea" autosize size="small" name="title" @change="updateRemarks(scope.row)" />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!--业绩爬虫-->
          <router-link
            v-if="scope.row.spiderType === 6"
            :to="'/crawler/yeji/' + scope.row.id"
          >
            <el-button
              size="medium"
              type="text"
              icon="el-icon-edit"
            >
              爬虫详情
            </el-button>
          </router-link>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      background
      :current-page="page"
      :total="total"
      :page-size="limit"
      :page-sizes="[10, 20, 50, 100]"
      prev-text="上一页"
      next-text="下一页"
      style="padding: 30px 0; text-align: center"
      layout="total, sizes, prev, pager, next, jumper"
      @size-change="changePageSize"
      @current-change="changeCurrentPage"
    />

  </div>
</template>

<script>
import crawlerApi from '@/api/crawler/crawler'
import { mapGetters } from 'vuex'
import variables from '@/styles/variables.scss'
import axios from 'axios'

export default {
  name: 'YeJiList',
  data() {
    return {
      list: null, // 数据列表
      total: 0, // 数据库总记录数
      page: 1, // 默认页码
      limit: 10, // 每页记录数

      // 人员列表
      personList: [],

      // 爬虫类型列表
      spiderTypeList: [
        // {
        //   value: 0,
        //   label: '国内招中标数据'
        // },
        // {
        //   value: 1,
        //   label: '海外招中标数据'
        // },
        // {
        //   value: 2,
        //   label: '在线投资与审批平台'
        // },
        // {
        //   value: 3,
        //   label: '物资采购'
        // },
        // {
        //   value: 4,
        //   label: '首页爬虫'
        // },
        // {
        //   value: 5,
        //   label: '政策新闻'
        // },
        {
          value: 6,
          label: '业绩爬虫'
        }
        // {
        //   value: 7,
        //   label: '企业备案爬虫'
        // }
      ],
      // 服务器列表
      machineList: [],

      // 项目名称列表
      projectNameList: [],

      // 查询条件
      searchObj: {
        codeName: '',
        isJava: -1,
        spiderType: 6, // 爬虫类型
        orderBys: {
          'orderColumn': 'updateCount',
          'order': 'DESC'
        },
        person: '',
        userId: 0 // 数据置顶用的当前登录的用户的id
        // 多列排序用
        // sortField: {},
        // orderBys: [
        //   {
        //     'orderColumn': 'errCount',
        //     'order': 'DESC'
        //   }
        // ]
      },

      // 预览弹窗展示
      dialogTableVisible: false,

      // 预览列表
      previewList: [],
      multipleSelection: [], // 多选

      // 表格数据加载遮罩
      loading: true,

      // 时间选取
      gmtCreate: [], // 选中的时间
      pickerOptions: { // 时间选择器
        shortcuts: [
          {
            text: '今日',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          }, {
            text: '两个月以上',
            onClick(picker) {
              const end = new Date()
              const start = new Date('2000-01-01')
              end.setTime(end.getTime() - 3600 * 1000 * 24 * 60)
              picker.$emit('pick', [start, end])
            }
          }]
      },

    }
  },

  watch: {
    codeNameChange(value, oldValue) {
      if (!value && oldValue !== '') {
        this.fetchDataChange(1)
      }
    }
  },

  computed: {
    ...mapGetters([
      'id',
      'name',
      'roles',
      'person'
    ]),
    codeNameChange() {
      return this.searchObj.codeName
    }
  },

  created() {
    this.searchObj.userId = this.id
    this.searchObj.person = this.person
    this.fetchData()
    this.fetchList()
  },

  methods: {
    fetchList() {
      crawlerApi.getPersonList().then((response) => {
        this.personList = response.data.result
      })
      crawlerApi.getMachineList(this.searchObj.person, this.searchObj.spiderType).then((response) => {
        this.machineList = response.data.result
      })
      crawlerApi.getProjectNameList(this.searchObj.person, this.searchObj.spiderType).then((response) => {
        this.projectNameList = response.data.result
      })
    },

    fetchDataChange(page) {
      this.page = page
      this.fetchData()
    },

    fetchData() {
      this.loading = true
      crawlerApi.listPage(this.page, this.limit, this.searchObj).then((response) => {
        const list = response.data.result.list
        // eslint-disable-next-line no-return-assign
        list.map(item => item.lastTime = Number(item.lastTime))
        this.list = list
        this.total = response.data.result.total
        this.loading = false
      })
      this.$nextTick(() => {
        this.$refs.fetchData.$el.blur()
      })
    },

    changePerson() {
      this.fetchList()
      this.fetchDataChange(1)
    },

    // 每页展示条数的改变，size：回调函数, 表示当前选中的展示条数
    changePageSize(size) {
      this.limit = size
      this.fetchDataChange(1)
    },

    // 翻页，page：回调函数, 表示当前选中的页码
    changeCurrentPage(page) {
      this.page = page
      this.fetchData()
    },

    // 重置搜索表单
    resetData() {
      this.searchObj.codeName = ''
      this.searchObj.projectName = ''
      this.searchObj.machine = ''
      this.searchObj.spiderType = 6
      this.searchObj.isJava = -1
      this.searchObj.orderBys.orderColumn = ''
      this.searchObj.orderBys.order = ''
      this.gmtCreate = []
      this.searchObj.startTime = ''
      this.searchObj.endTime = ''
      this.page = 1
      this.limit = 10
      // this.$refs.tableList.clearSort()
      this.$refs.tableList.sort('updateCount', 'descending')
      // this.fetchData()
      this.$nextTick(() => {
        this.$refs.resetData.$el.blur()
      })
    },

    // 表头style
    headStyle() {
      return 'color: black; backgroundColor: ' + variables.globalStyle
    },

    // 列style
    cellStyle({ row, column, rowIndex, columnIndex }) {
      if (row.isTop === 1) {
        return 'backgroundColor: #f2f2f2; height: 50px'
      } else {
        return 'height: 50px'
      }
    },

    // 触发排序
    handleSortChange({ order, prop }) {
      // (单列排序)
      this.searchObj.orderBys.orderColumn = prop
      if (order === 'ascending') {
        this.searchObj.orderBys.order = 'ASC'
      } else if (order === 'descending') {
        this.searchObj.orderBys.order = 'DESC'
      } else {
        this.searchObj.orderBys.orderColumn = ''
        this.searchObj.orderBys.order = ''
      }
      this.page = 1
      this.fetchData()
      // // (多列排序)触发的排序和已经保存的排序相同时，取消该字段的排序
      // if (!order || this.searchObj.sortField[prop] === order) {
      //   this.searchObj.sortField[prop] = null
      // } else {
      //   this.searchObj.sortField[prop] = order
      // }
      // console.log(this.searchObj.sortField)
      //
      // this.searchObj.orderBys = [] // 需要排序的字段列表
      // let direction = '' // 传给的后端参数
      // for (const i in this.searchObj.sortField) {
      //   if (this.searchObj.sortField[i] === 'ascending') {
      //     direction = 'ASC'
      //   } else if (this.searchObj.sortField[i] === 'descending') {
      //     direction = 'DESC'
      //   } else {
      //     direction = ''
      //   }
      //   if (direction !== '') {
      //     this.searchObj.orderBys.push({
      //       'orderColumn': i,
      //       'order': direction
      //     })
      //   }
      // }
      // console.log(this.searchObj.orderBys)
      // // 调用接口
      // this.fetchData()
    },

    // handleHeadAddClass({ column }) {
    //   if (this.searchObj.sortField[column.property]) {
    //     column.order = this.searchObj.sortField[column.property]
    //   }
    // },

    // 关闭弹窗
    closeDialogVisable(previewList) {
      this[previewList] = []
    },

    // 多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },

    // 置顶
    toppingData() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        })
      } else {
        // 获取id集合
        const arr = []
        this.multipleSelection.forEach(item => {
          arr.push(item.id)
        })

        // 创建表单
        const formData = new FormData()
        formData.append('arr', arr)
        formData.append('userId', this.searchObj.userId)

        crawlerApi.toppingData(formData).then((response) => {
          if (response.code === 200) {
            this.$message({
              message: '置顶成功',
              type: 'success'
            })
            this.fetchDataChange(1)
          } else {
            this.$message({
              message: response.message,
              type: 'error'
            })
          }
        })
      }
      this.$nextTick(() => {
        this.$refs.toppingData.$el.blur()
      })
    },

    // 取消置顶
    unToppingData() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请选择数据',
          type: 'warning'
        })
      } else {
        // 获取id集合
        const arr = []
        const arr2 = [] // 判断是否选择了未置顶数据
        this.multipleSelection.forEach(item => {
          if (item.isTop === 0) {
            arr2.push(item.id)
          } else {
            arr.push(item.id)
          }
        })

        if (arr2.length > 0) {
          this.$message({
            message: '请勿选择未置顶数据',
            type: 'error'
          })
        } else {
          // 创建表单
          const formData = new FormData()
          formData.append('arr', arr)
          formData.append('userId', this.searchObj.userId)

          crawlerApi.unToppingData(formData).then((response) => {
            if (response.code === 200) {
              this.$message({
                message: '取消成功',
                type: 'success'
              })
              this.fetchDataChange(1)
            } else {
              this.$message({
                message: response.message,
                type: 'error'
              })
            }
          })
        }
      }
      this.$nextTick(() => {
        this.$refs.unToppingData.$el.blur()
      })
    },

    // 跳转链接
    linkOut(jobId) {
      const outurl = "http://192.168.1.221:8080/xxl-job-admin/joblog?jobId=" + jobId;
      window.open(outurl, '_blank')
    },

    // 联想搜索
    querySearchAsync(queryString, cb) {
      let list = []
      if (!queryString) {
        cb(list)
        return
      } else {
        crawlerApi.querySearchAsync(queryString, this.searchObj.person, this.searchObj.spiderType).then((response) => {
          if (response.code === 200) {
            list = response.data.list
            cb(list)
          }
        })
      }
    },

    // 修改备注信息
    updateRemarks(row) {
      if (row.remarks) {
        const date = new Date()
        const year = date.getFullYear()
        const month = (date.getMonth() + 1).toString().padStart(2, '0')
        const day = date.getDate().toString().padStart(2, '0')
        const result = `${year}-${month}-${day}`
        row.remarks = row.remarks + ' ' + result
      } else {
        row.remarks = ''
      }
      crawlerApi.updateRemarks(row.id, row.remarks).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '备注修改成功',
            type: 'success'
          })
          this.fetchData()
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: 'error'
        })
      })
    },

    // 最近运行时间筛选
    changeGmtCreate() {
      if (this.gmtCreate != null) {
        this.searchObj.startTime = this.gmtCreate[0]
        this.searchObj.endTime = this.gmtCreate[1]
        this.fetchDataChange(1)
      } else {
        this.searchObj.startTime = ''
        this.searchObj.endTime = ''
        this.fetchDataChange(1)
      }
    },

    // 修改负责人
    updatePerson(row) {
      crawlerApi.updatePerson(row.id, row.person).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '负责人修改成功',
            type: 'success'
          })
          this.fetchData()
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: 'error'
        })
      })
    },

    updatePerson2(id, person) {
      crawlerApi.updatePerson(id, person).then((response) => {
        if (response.code === 200) {
          this.$message({
            message: '负责人修改成功',
            type: 'success'
          })
          this.fetchData()
        }
      }).catch((err) => {
        this.$message({
          message: err.message,
          type: 'error'
        })
      })
    }

  }
}
</script>

<style lang="scss" scoped>

</style>
<style>
  .right-toolbarClass {
    flex: 1;
    text-align: right;
  }
  .box-card {
    width: 480px;
  }
  .el-loading-mask {
    z-index: 1;
    /*background-color: rgb(255,255,255,0);*/
  }
</style>
